<?php
/**
 * 分公司码管理
 * @author liangpan
 */
include_once dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'public.class.php';
class nl_sp extends nl_public
{
	
	static $base_table='nns_mgtvbk_sp';
	static $cp_table='nns_cp';
	
	static $arr_filed = array(
	    'nns_id',
	    'nns_name',
	    'nns_contact',
	    'nns_telphone',
	    'nns_email',
	    'nns_rule',
	    'nns_config',
	    'nns_state',
	    'nns_create_time',
	    'nns_modify_time',
	    'nns_bind_cp',
	);
	/**
	 * 查询列表
	 *@param $dc
	 *@param $start
	 *@param $size
	 *@param $like
	 *@return array
	 */
	static public function query($dc,$params=null,$page_info=null)
	{
		if(isset($params['where']) && !empty($params['where']))
		{
			foreach ($params['where'] as $where_key=>$where_val)
			{
				self::$str_where.=" {$where_key} like '%{$where_val}%' and ";
			}	
		}
		if(isset($params['like']) && !empty($params['like']))
		{
			foreach ($params['like'] as $like_key=>$like_val)
			{
				self::$str_where.=" {$like_key} like '%{$like_val}%' and ";
			}
		}
		self::$str_where = (strlen(self::$str_where) > 5) ? trim(self::$str_where,'and ') : '';
		$str_limit = self::make_page_limit($page_info);
		$sql="select * from " . self::$base_table . " " . self::$str_where . " {$str_limit} ";
		$sql_count = "select count(*) as count from " . self::$base_table . " " . self::$str_where;
		$result_count = nl_query_by_db($sql_count,  $dc->db());
		$result = nl_query_by_db($sql, $dc->db());
		self::init_where();
		if(!$result)
		{
			return self::return_data(1,"查询数据失败".$sql);
		}
		if(!$result_count)
		{
			return self::return_data(1,"查询数据失败".$sql_count);
		}
		return self::return_data(0,"查询数据成功",$result,$result_count);
	}
	
	/**
	 * 查询所有
	 * @param  $dc
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据'), multitype:NULL number string , number, mixed, multitype:NULL multitype:a r y s t i n g  array multitype:number  >
	 */
	static public function query_all($dc)
	{
		$sql="select * from " . self::$base_table;
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,"查询数据失败".$sql);
		}
		return self::return_data(0,"查询数据成功",$result);
	}
	
	/**
	 * 查询单个列表
	 * @param object $dc 数据库对象
	 * @param string $nns_id guid
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function query_by_id($dc,$nns_id)
	{
		if(empty($nns_id))
		{
			return self::return_data(1,'id为空');
		}
		$sql="select * from " . self::$base_table . " where nns_id='{$nns_id}' limit 1";
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,"查询数据失败".$sql);
		}
		return self::return_data(0,"查询数据成功:".$sql,$result);
	}
	
	/**
	 * 查询某个CP被多少个SP绑定
	 * @param unknown $dc
	 * @param unknown $cp_id
	 */
	static public function get_cp_bind_sp_info($dc,$cp_id)
	{
	    if(empty($cp_id))
	    {
	        return self::return_data(1,'cpid为空');
	    }
	    $sql="select group_concat(nns_id) as group_concat_sp_id from " . self::$base_table . " where nns_bind_cp like '%,{$cp_id},%' limit 1";
	    $result = nl_query_by_db($sql, $dc->db());
	    if(!$result)
	    {
	        return self::return_data(1,"查询数据失败".$sql);
	    }
	    $result = (isset($result[0]) && is_array($result[0]) && !empty($result[0])) ? $result[0] : null;
	    return self::return_data(0,"查询数据成功:".$sql,$result);
	}
	
	/**
	 * 查询单个列表
	 * @param object $dc 数据库对象
	 * @param string $nns_id guid
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function query_by_ids($db,$nns_id)
	{
	    if(empty($nns_id) || !is_array($nns_id))
	    {
	        return self::return_data(1,'id为空');
	    }
	    $sql="select * from " . self::$base_table . " where nns_id in('" . implode("','", $nns_id) . "')";
	    $result = nl_query_by_db($sql, $db);
	    if(!$result)
	    {
	        return self::return_data(1,"查询数据失败".$sql);
	    }
	    return self::return_data(0,"查询数据成功",$result);
	}
	
	/**
	 * 查询SP表是否有绑定的Cp数据
	 * @param object $dc 数据库对象
	 * @param string $cp_id cp_id
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function query_is_bind_cp($dc,$cp_id)
	{
		if(strlen($cp_id) < 1)
		{
			return self::return_data(1,'cp_id为空');
		}
		$sql="select count(*) as count from " . self::$base_table . " where nns_bind_cp='{$cp_id}' limit 1";
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,"查询数据失败".$sql);
		}
		$result = isset($result[0]['count']) ? $result[0]['count'] : 0;
		return self::return_data(0,"查询数据成功",$result);
	}
	/**
	 * 查询SP表是否有绑定的Cp数据
	 * @param object $dc 数据库对象
	 * @param string $cp_id cp_id
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function query_bind_cp_info($dc,$cp_id)
	{
		if(strlen($cp_id) < 1)
		{
			return self::return_data(1,'cp_id为空');
		}
		$sql="select nns_id,nns_name,nns_bind_cp,nns_config from " . self::$base_table . " where nns_bind_cp like '%{$cp_id},%' ";
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,"查询数据失败".$sql);
		}
		return self::return_data(0,"查询数据成功",$result);
	}
	
	/**
	 * 解除绑定的Cp数据
	 * @param object $dc 数据库对象
	 * @param array $sp_id sp_id
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function unbind($dc,$sp_id)
	{
		if(empty($sp_id))
		{
			return self::return_data(1,'sp_id为空');
		}
		$sql = "update " . self::$base_table . " set nns_bind_cp='' where nns_id in ('" . implode("','", $sp_id) . "')";
		$result = nl_execute_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,"查询数据失败".$sql);
		}
		return self::return_data(0,"查询数据成功",$result);
	}
	
	/**
	 * 绑定的Cp数据
	 * @param object $dc 数据库对象
	 * @param string $sp_id sp_id
	 * @param string $cp_id cp_id
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function bind($dc,$sp_id,$cp_id)
	{
		if(empty($sp_id))
		{
			return self::return_data(1,'sp_id为空');
		}
		$sql = "update " . self::$base_table . " set nns_bind_cp='{$cp_id}' where nns_id='{$sp_id}'";
		$result = nl_execute_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,"SP绑定失败".$sql);
		}
		return self::return_data(0,"SP绑定成功",$result);
	}
	
	/**
	 * 兼容老模式查询sp配置信息，但是如果CP里面有配置又和SP配置参数一样，以Cp配置为准
	 * @param object $dc 数据库操作对象
	 * @param string $sp_id Spid
	 * @param string $is_col 是否查询出一条数据 false 返回数据库查询的所有信息（二维数组） | true 只返回数据库查询的一条信息（一维数组）
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function query_compatible($dc,$sp_id=null,$is_col=false)
	{
		$sql="select * from " . self::$base_table ;
		if(!empty($sp_id))
		{
			$sql.=" where nns_id ='{$sp_id}' ";
		}
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,"查询SP列表信息数据库执行失败,sql:".$sql);
		}
		if(empty($result) || !is_array($result))
		{
			return self::return_data(0,"ok",$result);
		}
		$temp_arr_cp = array();
		foreach ($result as $key=>$val)
		{
			if(!isset($temp_arr_cp[$val['nns_bind_cp']]))
			{
				$sql_cp = "select * from " . self::$cp_table . " where nns_id='{$val['nns_bind_cp']}' limit 1";
				$result_cp = nl_query_by_db($sql_cp, $dc->db());
				if(!$result_cp)
				{
					return self::return_data(1,"查询CP列表信息数据库执行失败,sql:".$sql);
				}
				$result_cp = (isset($result_cp[0]) && !empty($result_cp[0])) ? $result_cp[0] : null;
				$result_cp['nns_config'] = (isset($result_cp['nns_config']) && !empty($result_cp['nns_config'])) ? json_decode($result_cp['nns_config'],true) : null;
				$temp_arr_cp[$val['nns_bind_cp']] = $result_cp;
			}
			$val['sp_config'] = (isset($val['nns_config']) && !empty($val['nns_config'])) ? json_decode($val['nns_config'],true) : null;
			unset($val['nns_config']);
			$result[$key] = $val;
			$result[$key]['cp_config'] = $temp_arr_cp[$val['nns_bind_cp']];
		}
		foreach ($result as $k=>$v)
		{
			if(empty($v['cp_config']))
			{
				$result[$k]['nns_config'] = $v['sp_config'];
			}
			else if(empty($v['sp_config']))
			{
				$result[$k]['nns_config'] = $v['cp_config'];
			}
			else
			{
				$result[$k]['nns_config'] = self::compare_config( $v['sp_config'],  $v['cp_config']);
			}
			unset($result['cp_config']);
			unset($result['sp_config']);
		}
		if($is_col)
		{
			$result = isset($result[0]) ? $result[0] : null;
		}
		return self::return_data(0,"ok",$result);
	}
	
	/**
	 * 对比数据返回数组
	 * @param array $sp_config sp配置数据数组
	 * @param array $cp_config cp配置数据数组
	 * @return array
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function compare_config($sp_config,$cp_config)
	{
		$arr_config = $sp_config;
		foreach ($cp_config as $key=>$val)
		{
			if(!is_array($val))
			{
				if(strlen($val) > 0)
				{
					$arr_config[$key]=$val;
				}
			}
			else
			{
				$arr_config[$key] = self::compare_config(null, $val);
			}
		}
		return $arr_config;
	}

	/**
	 * 删除
	 * @param object $dc 数据库对象
	 * @param string $sp_id SPID
	 * @param string $cp_id CPID
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author xingcheng.hu
	 * @date 2016-03-09
	 */
	static public function update_bind_cp_by_sp($dc,$sp_id,$cp_id)
	{
		if(strlen($sp_id) < 1)
		{
			return self::return_data(1,'sp_id为空');
		}
		$sql = "update ".self::$base_table." set nns_bind_cp='{$cp_id}' where nns_id='{$sp_id}'";
		$result = nl_query_by_db($sql, $dc->db());;
		if(!$result)
		{
			return self::return_data(1,"更新SP绑定CP失败".$sql);
		}
		return self::return_data(0,"更新SP绑定CP成功",$result);
	}
	
	/**
	 * 查询单挑SP的基本信息
	 * @param object $dc 数据库对象
	 * @param string $sp_id sp_id
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-09-10
	 */
	static public function get_sp_config($dc, $sp_id=null)
	{
		if(strlen($sp_id) < 1)
		{
			return self::return_data(1,"sp id 错误，传入参数为：".var_dump($sp_id,true));
		}
		$result_info=self::query_by_id($dc, $sp_id);
		if($result_info['ret'] !=0)
		{
			return self::return_data(1,"sp id 查询 sql 错误：".var_dump($result_info['reason'],true));
		}
		$last_config = null;
		
		$result_info = isset($result_info['data_info'][0]) ? $result_info['data_info'][0] : null;
		if(isset($result_info['nns_config']) && strlen($result_info['nns_config']) >0)
		{
			$result_info_config = json_decode($result_info['nns_config'],true);
			$last_config['nns_config']=(is_array($result_info_config) && !empty($result_info_config)) ?  $result_info_config : null;
			unset($result_info['nns_config']);
		}
		if(is_array($result_info) && !empty($result_info))
		{
			foreach ($result_info as $key=>$val)
			{
				$last_config['base_info'][$key] = $val;
			}
		}
		return self::return_data(0,"ok",$last_config);
	}
	
	/**
	 * 修改CP
	 * @param object $dc 数据库对象
	 * @param array $params 数据数组
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-03-06
	 */
	static public function edit($dc,$params,$nns_id)
	{
	    $nns_id = is_array($nns_id) ? $nns_id : array($nns_id);
	    if(empty($nns_id))
	    {
	        return self::return_data(1,'全局错误日志_id为空');
	    }
	    $params = self::except_useless_params(self::$arr_filed, $params);
	    if(empty($params))
	    {
	        return self::return_data(1,'参数为空');
	    }
	    $params['nns_modify_time'] = date("Y-m-d H:i:s");
	    $sql = self::make_update_sql(self::$base_table, $params,array('nns_id'=>$nns_id));
	    $result = nl_execute_by_db($sql, $dc->db());
	    if(!$result)
	    {
	        return self::return_data(1,'数据库执行失败'.$sql);
	    }
	    return self::return_data(0,'ok');
	}
	
	
	/**
	 * 依据条件查询分集信息
	 * @param $dc
	 * @param $params
	 * @return array
	 */
	static public function query_by_condition($dc, $params)
	{
	    $params = self::except_useless_params(self::$arr_filed, $params);
	    if (!is_array($params) || empty($params))
	    {
	        return self::return_data(1, '查询条件为空不允许查询');
	    }
	    $sql = self::make_query_sql(self::$base_table, $params);
	    $result = nl_query_by_db($sql, $dc->db());
	    if (!$result)
	    {
	        return self::return_data(1, '数据库查询失败,sql:' . $sql);
	    }
	    $result = (isset($result) && !empty($result)) ? $result : null;
	    return self::return_data(0, 'OK' . $sql, $result);
	}
}